package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/7/9 22:21
 */

@Service(version = "1.0.0")
public class VisitorApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    /**
     * 保存访客：
     *
     * @param userId
     * @param visitorUserId
     * @param from
     * @return
     */
    @Override
    public String saveVisitors(Long userId, Long visitorUserId, String from) {

        if (ObjectUtil.isAllEmpty(userId, visitorUserId, from)) {
            return null;
        }
        //首先判断是否今日已经保存过此visitorUser:
        //查询访客用户在今天是否已经记录过，如果已经记录过，不再记录
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();
        Query query = Query.query(Criteria.where("userId").is(userId).and("visitorUserId").is(visitorUserId)
                .andOperator(Criteria.where("date").gte(minDate),
                        Criteria.where("date").lte(maxDate))
        );
        long count = mongoTemplate.count(query, Visitors.class);
        if (count > 0) {
            return null;
        }

        Visitors visitors = new Visitors();
        visitors.setId(new ObjectId());
        visitors.setUserId(userId);
        visitors.setVisitorUserId(visitorUserId);
        visitors.setFrom(from);
        visitors.setDate(System.currentTimeMillis());
        mongoTemplate.save(visitors);

        return visitors.getId().toHexString();
    }


    /**
     * 查询访客列表：
     *
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> queryMyVisitor(Long userId) {

        // 查询前5个访客数据，按照访问时间倒序排序
        // 如果用户已经查询过列表，记录查询时间，后续查询需要按照这个时间往后查询

        // 上一次查询列表的时间
        Long date = Convert.toLong(redisTemplate.opsForHash().get(VISITOR_REDIS_KEY, String.valueOf(userId)));

        //分页查询前五条按时间倒序：
        PageRequest pageRequest = PageRequest.of(0, 5, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(pageRequest);
        if (ObjectUtil.isNotEmpty(date)) {
            query.addCriteria(Criteria.where("date").gte(date));
        }

        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);
        //查询每个来访用户的得分
        for (Visitors visitors : visitorsList) {

            Query queryScore = Query.query(Criteria.where("toUserId")
                    .is(userId).and("userId").is(visitors.getVisitorUserId())
            );
            //查询推荐用户表：条件：toUserId就是本机自己，userId就是来访的人。
            RecommendUser recommendUser = this.mongoTemplate.findOne(queryScore, RecommendUser.class);
            if (ObjectUtil.isNotEmpty(recommendUser)) {
                visitors.setScore(recommendUser.getScore());
            } else {
                //默认得分
                visitors.setScore(90d);
            }
        }

        return visitorsList;
    }


    /**
     * 分页查询我的访客：
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Visitors> findVisitorsList(Long userId, Integer page, Integer pageSize) {

        PageInfo<Visitors> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);

        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        if (visitors.size() == 0) {
            return pageInfo;
        }

        //不为空：
        pageInfo.setRecords(visitors);


        //查询完，给redis 记录查询时间
        String redisKey = VISITOR_REDIS_KEY;
        String hashKey = userId.toString();
        String dateValue = String.valueOf(System.currentTimeMillis());
        redisTemplate.opsForHash().put(redisKey, hashKey, dateValue);

        return pageInfo;
    }
}

